/**
 * 
 * namespace 表示在全局 state 上的 key
 * state 是初始值，在这里是空数组
 * reducers 等同于 redux 里的 reducer，接收 action，同步更新 state
 * 
 */
import $http from "../utils/api";

export default {
    namespace: 'products',
    state: [
        { name: 'fenglong' }
    ],
    effects: {
        *addAsycn(payload, { call, put, select }) {
            let res = yield call($http, '调用')
            yield console.log(res);
            console.log(yield select(state => state.products), payload);
            yield put({ type: 'add', obj: {} });
            console.log(11123);
        }
    },
    reducers: {
        'delete'(state, { payload: id }) {
            console.log(state, id);
            return state.filter(item => item.id !== id);
        },
        'add'(state, { obj }) {
            let objClone = JSON.parse(JSON.stringify(state))
            objClone.push(obj = {
                name: `fenglong${state.length}`,
                id: state.length + 1
            })
            return objClone
        }

    },
    subscriptions: {
        setup({ dispatch, history }) {
            console.log(history, 'history');
            history.listen(({ pathname }) => {
                if (pathname == '/products') {
                    dispatch({
                        type: 'add',
                        obj: {}
                    })
                }
            })
        }
    }
};